<?php

namespace api\libs\swoft;

use api\libs\swoft\core\SwoftCore;
use api\libs\swoft\ifc\SwoftClient;
use Yii;
use yii\web\UploadedFile;
use api\modules\app\resource\MaterialResource;

class SwoftMaterial extends SwoftClient
{
    public function upload($access_token) {
        $file_path = $this->uploadFile();
        $options[SwoftCore::SWOFT_RESOURCE] = $this->getBaseUri() . 'web/upload-origin-imgs';
        $options[SwoftCore::SWOFT_QUERY_STRING] = array('token' => $access_token);
        $options[SwoftCore::SWOFT_METHOD] = SwoftCore::SWOFT_HTTP_POST;
        $options[SwoftCore::SWOFT_CONTENT_TYPE] = 'multipart/form-data';
        $file_data = ['imgs' => new \CURLFile($file_path)];
        $options[SwoftCore::SWOFT_FILE] = $file_data;
        return $this->sendRequest($options);
    }
    
    public function uploadFile() {
        $model = new \api\modules\internal\models\Material;
        $model->file = UploadedFile::getInstanceByName('file');
        if ($model->validate()) {
            $file_name = time() . '_' . rand(1000, 9999) . '.' . $model->file->extension;
            $temp_path = $model->base_path . '/' . $file_name;
            $model->file->saveAs($temp_path);
            return $temp_path;
        } else {
            throw new ServerErrorHttpException('SAVE TEMP IMAGE ERROR');
        }
    }
}